//#define __DEBUG__
// by Rommel
#define THIS_FILE "fn_searchnearby.sqf"
#include "x_setup.sqf"

__TRACE_1("_this","_this")

private ["_group", "_leader", "_behaviour", "_array", "_building", "_indices", "_count", "_units", "_timeout", "_unit", "_gstate"];
_group = (_this select 0) call FUNC(getgroup);
_gstate = _group getVariable [QGVAR(gstate), 2];
if (_gstate == 2) exitWith {};
_group lockWp true;
private ["_leader","_behaviour"];
_leader = leader _group;
_behaviour = behaviour _leader;
_group setBehaviour "combat";

private ["_array", "_building", "_indices"];
_array = _leader call FUNC(getnearestbuilding);
if (count _array < 2) exitWith {_group lockwp false};
_building = _array select 0;
if (_leader distance _building > 200) exitWith {_group lockWp false};
__TRACE_2("Start","_group","_array")
_indices = _array select 1;
_group setFormdir ([_leader, _building] call FUNC(DirTo));

private ["_count","_units"];
_units = units _group;
_count = (count _units) - 1;

_timeout = time + 450;
__TRACE_1("_indices","_indices");

#ifdef __DEBUG__
	[format["searchnearby_%1",_group], getPosASL _leader,"ICON","ColorRed",[0.7,0.7],"",0,"n_inf"] call FUNC(CreateMarkerLocal);
#endif

while {_indices > 0 && {_count > 0} && {_timeout > time}} do {
	sleep 10;
	while {_indices > 0 && {_count > 0} && {_timeout > time}} do {
		private "_unit";
		_unit = _units select _count;
		if (unitReady _unit) then {
			_unit commandMove (_building buildingPos _indices);
			sleep 1;
			_unit doMove (_building buildingPos _indices);
			__DEC(_indices);
		};
		__DEC(_count);
	};
	_units = units _group;
	_count = (count _units) - 1;
};
waituntil {sleep 3;	{unitReady _x} count _units >= count (units _group) - 1 || {(_units call FUNC(GetAliveUnits)) == 0} || {time > _timeout}};
if ((_units call FUNC(GetAliveUnits)) > 0) then {
	{_x doFollow _leader} forEach _units;
	_group setBehaviour _behaviour;
	_group lockWp false;
};
__TRACE_2("End","_group","_array")